//
//  StatusListViewModel.swift
//  weibo
//
//  Created by 上官风雨 on 15/11/16.
//  Copyright © 2015年 上官风雨. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
import SDWebImage

class StatusListViewModel: NSObject {
    
    
    class  func loadData(since_id since_id : Int , max_id : Int ,finished:(array:[Status]?)->()){
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        guard let token = UserAccountViewModel().token else{
            
            SVProgressHUD.showErrorWithStatus("您未登录...")
            return
        }
        
        var parameters = ["access_token" : token]
        let tool = NetworkTools.tools
        
        if since_id > 0 {
            
            parameters["since_id"] = "\(since_id)"
        }
        if max_id > 0 {
            
            parameters["max_id"] = "\(max_id)"
            
        }
//        [1]	(null)	"NSErrorFailingURLKey" : "https://api.weibo.com/2/statuses/home_timeline.json?access_token=2.00oydoIDIBQzEE59e6a07275hoLt9C"	
        
        tool.requestJsonDict(.Get, urlString: urlString, parameters: parameters) { (result, error) -> () in
            
            if error != nil{
                
                finished(array: nil)
                return
            }
            
            var list = [Status]()
            if let array = result!["statuses"] as? [[String : AnyObject]]{
                
                for item in array {
                    
                    let s = Status(dict: item)
                    
                    list .append(s)
                }
                
//                finished(array: list)
                cacheStatusImages(list, finished: finished)
            }
            
            
        }
        
    }
    
    class func cacheStatusImages(array: [Status],finished:(array:[Status]?)->()){
        
        if array.count == 0 {
            finished(array: array)
            return
        }
        
        //创建群组
        let group = dispatch_group_create()
        for s in array {
            
            if let imageUrl = s.imageURLs {
                
                if imageUrl.count != 1{
                    
                    continue
                }
                
                for url in imageUrl{
                    
                  dispatch_group_enter(group)
                    //下载图片
                    SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (_, _, _, _, _) -> Void in
                        
                        print("单张图片下载完成")
                        
                    dispatch_group_leave(group)
                    })
                }
            }
        }
        //在主线程完成回调
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            
            print("所有的图片下载完成")
            finished(array: array)
        }
        
    }
    
}
